<template>
  <div>
    <!-- <div class="toptitle">角色列表</div> -->
    <el-form
      :inline="true"
      :model="formInline"
      class="demo-form-inline"
      @keyup.enter.native="search()"
    >
      <el-form-item label="等级名称">
        <br />
        <br />
        <el-input
          v-model="formInline.gradelevelName"
          placeholder
          style="margin-left:-65px;width:200px"
        ></el-input>
      </el-form-item>
      <!-- <el-form-item label="等级编码：">
        <el-input v-model="formInline.gradelevelCode" placeholder style="width: 100%;"></el-input>
      </el-form-item>-->
      <el-form-item style="margin-left:700px;text-align:right;margin-top:50px">
        <el-button
          type="primary"
          @click="search()"
          size="mini"
          icon="el-icon-search"
          >查询</el-button
        >
        <!-- </el-form-item>
      <el-form-item> -->
        <el-button
          type="primary"
          @click="kong()"
          size="mini"
          icon="el-icon-delete"
          >清空</el-button
        >
        <!-- </el-form-item>
      <el-form-item> -->
        <el-button type="primary" @click="add()" size="mini" icon="el-icon-edit"
          >新增等级规则</el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      :data="tableData"
      border
      stripe
      v-loading="loading"
      style="width: 100%"
      :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
    >
      <el-table-column
        type="index"
        width="60"
        label="序号"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="gradelevelName"
        label="会员等级名称"
        width="100"
        align="left"
      ></el-table-column>
      <el-table-column
        prop="yearTotalConsume"
        label="升级累计消费下限"
        align="left"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.yearTotalConsume != null">{{
            scope.row.yearTotalConsume
          }}</span>
          <span v-if="scope.row.yearTotalConsume == null">-</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="degradeMoney"
        label="降级累计消费上限"
        align="left"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.degradeMoney != null">{{
            scope.row.degradeMoney
          }}</span>
          <span v-if="scope.row.degradeMoney == null">-</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="degradeDay"
        label="降级天数"
        width="50"
        align="left"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.degradeDay != null">{{
            scope.row.degradeDay
          }}</span>
          <span v-if="scope.row.degradeDay == null">-</span>
        </template>
      </el-table-column>
      <el-table-column prop="scoreRatio" label="积分权益(倍积分)" align="left">
        <template slot-scope="scope">
          <span v-if="scope.row.scoreRatio != null">{{
            scope.row.scoreRatio
          }}</span>
          <span v-if="scope.row.scoreRatio == null">-</span>
        </template>
      </el-table-column>
      <el-table-column prop="birthRatio" label="生日权益(倍积分)" align="left">
        <template slot-scope="scope">
          <span v-if="scope.row.birthRatio != null">{{
            scope.row.birthRatio
          }}</span>
          <span v-if="scope.row.birthRatio == null">-</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="firstScore"
        label="首次达成礼(赠送积分)"
        align="left"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.firstScore != null">{{
            scope.row.firstScore
          }}</span>
          <span v-if="scope.row.firstScore == null">-</span>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="levelNumber" label="排序" width="50" align="left"></el-table-column> -->
      <el-table-column label="背景图">
        <template slot-scope="scope">
          <div @click="handlePictureCardPreview(scope.row)">
            <el-image style="width: 80px; height: 80px" :src="scope.row.backgroundImage" fit="conver" ></el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="updateTime"
        label="最后更新时间"
        align="right"
        width="180"
      ></el-table-column>
      <!-- <el-table-column prop="status" label="状态" align="center">
        <template slot-scope="scope">{{scope.row.status===0?'停用':'启用'}}</template>
            </el-table-column>-->
      <el-table-column label="操作" width="200" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" @click="edit(scope.row)" type="text"
            >编辑</el-button
          >
          <el-button @click="handledelete(scope.row)" type="text" size="mini"
            >删除</el-button
          >
          <!-- <el-button
            size="mini"
            @click="handleClick(scope.row)"
            v-if="scope.row.status===0"
            type="text"
          >启用</el-button>
          <el-button
            size="mini"
            @click="handleClick(scope.row)"
            v-if="scope.row.status===1"
            type="text"
          >停用</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="等级规则" :visible.sync="dialogVisible" width="40%">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="200px"
      >
        <el-form-item label="等级名称" prop="gradelevelName">
          <el-input v-model="ruleForm.gradelevelName"></el-input>
        </el-form-item>
        <el-form-item label="升级累计消费下限" prop="yearTotalConsume">
          <el-input
            v-model="ruleForm.yearTotalConsume"
            onkeyup="this.value=this.value.replace(/[^\d.]/g,'');"
            maxlength="8"
            placeholder="值为空则表示无论消费多少都不再升级"
            style="text-align-last:right"
          ></el-input>
        </el-form-item>
        <el-form-item label="降级累计消费上限" prop="degradeMoney">
          <el-input
            v-model="ruleForm.degradeMoney"
            onkeyup="this.value=this.value.replace(/[^\d.]/g,'');"
            maxlength="7"
            placeholder="值为空则表示无论消费多少都不再升级"
            style="text-align-last:right"
          ></el-input>
        </el-form-item>
        <el-form-item label="降级天数" prop="degradeDay">
          <el-input
            v-model="ruleForm.degradeDay"
            style="text-align-last:right"
          ></el-input>
        </el-form-item>
        <el-form-item label="积分权益(倍积分)" prop="scoreRatio">
          <el-input
            v-model="ruleForm.scoreRatio"
            style="text-align-last:right"
          ></el-input>
        </el-form-item>
        <el-form-item label="生日权益(倍积分)" prop="birthRatio">
          <el-input
            v-model="ruleForm.birthRatio"
            style="text-align-last:right"
          ></el-input>
        </el-form-item>
        <el-form-item label="首次达成礼(赠送积分)" prop="firstScore">
          <el-input
            v-model="ruleForm.firstScore"
            style="text-align-last:right"
          ></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="levelNumber">
          <el-input
            v-model="ruleForm.levelNumber"
            style="text-align-last:right"
          ></el-input>
        </el-form-item>
        <el-form-item label="背景图" prop="backgroundImage">
          <el-row>
            <el-col style="margin: 10px;">
              <el-upload
                style="margin: 10px"
                :action="action"
                list-type="picture-card"
                :limit="1"
                :on-preview="handlePictureCardPreview"
                :on-success="upLoadPic"
                :on-change="handleImgChange"
                :file-list="imgList"
                :headers="headers"
                accept="image/*"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="confirmEdit()" size="small"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog title="提示" :visible.sync="dialogVisibleone" width="30%">
      <span>确认删除？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleone = false" size="small"
          >取 消</el-button
        >
        <el-button type="primary" @click="sure()" size="small">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="背景图" :visible.sync="backgroundImageShow" width="60%">
      <img :src="curImage" style="width: 100%; height: auto;" alt="">
      <span slot="footer">
        <el-button @click="backgroundImageShow = false">取 消</el-button>
      </span>
    </el-dialog>

    <div class="block" style="margin-top:2px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 20, 30, 50, 100]"
        :current-page="listQuery.current"
        :page-size="listQuery.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import {
  getmemberrule,
  addmemberrule,
  upmemberrule,
  delmemberrule,
  usebutton,
} from '@/api/membergrade';
import qs from 'qs';
export default {
  data() {
    return {
      loading: true,
      listQuery: {
        current: 1,
        size: 10,
      },
      tableData: [],
      total: 0,
      formInline: {
        // gradelevelCode: "",
        gradelevelName: '',
      },
      data5: [],
      data3: [],
      data4: [],
      defaultProps: {
        children: 'sub',
        label: 'name',
      },
      objone: {},

      multipleSelection: [],
      radio: '',
      rolefenid: '',
      selected: {},
      ruleForm: {
        gradelevelName: '',
        // gradelevelCode: "",
        gradelevelId: '',
        // status: "",
        createUser: '',
        updateUser: '',
        oneTimeComsume: '',
        yearTotalConsume: '',
        degradeMoney: '',
        degradeDay: '',
        scoreRatio: '',
        birthRatio: '',
        firstScore: '',
        levelNumber: '',
        backgroundImage: '',
      },
      uuid: '',
      roleid: '',
      dialogVisibleone: false,
      dialogVisibletwo: false,
      dialogVisible: false,
      ruledata: [],

      rules: {
        gradelevelName: [
          { required: true, message: '请输入等级名称', trigger: 'blur' },
        ],
        yearTotalConsume: [
          { required: true, message: '升级累计消费下限', trigger: 'blur' },
        ],
        degradeMoney: [
          { required: true, message: '降级累计消费上限', trigger: 'blur' },
        ],
        yearTotalConsume: [
          { required: true, message: '请输入', trigger: 'blur' },
        ],
        degradeMoney: [{ required: true, message: '请输入', trigger: 'blur' }],
        degradeDay: [{ required: true, message: '请输入', trigger: 'blur' }],
        scoreRatio: [{ required: true, message: '请输入', trigger: 'blur' }],
        birthRatio: [{ required: true, message: '请输入', trigger: 'blur' }],
        firstScore: [{ required: true, message: '请输入', trigger: 'blur' }],
        levelNumber: [{ required: true, message: '请输入', trigger: 'blur' }],
        backgroundImage: [
          { required: true, message: '请输入', trigger: 'change' },
        ],
      },

      // 上传图片相关配置
      action: `${process.env.VUE_APP_BASE_API}/api/file-service/v1/file/uploadFile`,
      headers: {
        token: localStorage.getItem('token'), //从cookie里获取token，并赋值  Authorization ，而不是token
      },
      imgList: [],
      curImage: '',
      backgroundImageShow: false
    };
  },
  mounted() {
    this._getmemberinfo();
  },
  methods: {
    blurscore() {
      if (this.ruleForm.yearTotalConsume < this.ruleForm.oneTimeComsume) {
        this.$message.error('升级单次消费下限不能大于升级累计消费下限');
      }
    },
    kong() {
      //   this.formInline.gradelevelCode = "";
      this.formInline.gradelevelName = '';
    },
    search() {
      let data = {
        size: this.listQuery.size,
        current: 1,
        condition: { gradelevelName: this.formInline.gradelevelName },
        ascs: [],
        descs: [],
      };
      getmemberrule(data).then((res) => {
        this.tableData = res.records;
        this.tableData.gradeLevel = parseInt(res.records.gradeLevel);
        this.total = res.total;
        console.log(res, 'ppe');
      });
    },
    // handleClick(v) {
    //   if (v.status === 0) {
    //     var uuid = 1;
    //   } else if (v.status === 1) {
    //     var uuid = 0;
    //   }
    //   let data = { uuid: v.uuid, status: uuid };
    //   usebutton(qs.stringify(data)).then(res => {
    //     this.$message({
    //       showClose: true,
    //       message: res.message,
    //       type: "success"
    //     });
    //     this._getmemberinfo();
    //   });
    // },
    handledelete(v) {
      let data = {
        uuid: v.uuid,
      };
      this.$confirm('确认删除吗？').then((_) => {
        delmemberrule(data).then((res) => {
          this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success',
          });
          this._getmemberinfo();
        });
      });
    },

    add() {
      this.dialogVisible = !this.dialogVisible;
      this.editflag = false;
      this.ruleForm.gradelevelName = '';
      this.ruleForm.gradelevelId = '';
      this.ruleForm.yearTotalConsume = '';
      this.ruleForm.oneTimeComsume = '';
      this.ruleForm.degradeMoney = '';
      this.ruleForm.degradeDay = '';
      this.ruleForm.scoreRatio = '';
      this.ruleForm.birthRatio = '';
      this.ruleForm.firstScore = '';
      this.ruleForm.levelNumber = '';
      this.ruleForm.backgroundImage = '';
      this.imgList = [];
    },
    edit(v) {
      this.ruleForm.gradelevelName = v.gradelevelName;
      this.ruleForm.gradelevelId = v.gradelevelId;
      this.ruleForm.createUser = v.createUser;
      this.ruleForm.updateUser = v.updateUser;
      this.ruleForm.yearTotalConsume = v.yearTotalConsume;
      this.ruleForm.oneTimeComsume = v.oneTimeComsume;
      this.ruleForm.degradeMoney = v.degradeMoney;
      this.ruleForm.degradeDay = v.degradeDay;
      this.ruleForm.scoreRatio = v.scoreRatio;
      this.ruleForm.birthRatio = v.birthRatio;
      this.ruleForm.firstScore = v.firstScore;
      this.ruleForm.levelNumber = v.levelNumber;
      this.ruleForm.backgroundImage = v.backgroundImage;
      this.imgList = [];
      if(v.backgroundImage){
        let data = {
          name: '',
          url: v.backgroundImage,
        }
        this.imgList.push(data)
      }

      this.dialogVisible = !this.dialogVisible;
      this.editflag = true;
      this.uuid = v.uuid;
    },
    confirmEdit(v) {
      if (
        this.ruleForm.gradelevelName == '' ||
        this.ruleForm.gradelevelName == null
      ) {
        this.$message.error('请输入等级名称');
        return;
      }
      if (
        this.ruleForm.yearTotalConsume == '' ||
        this.ruleForm.yearTotalConsume == null
      ) {
        this.$message.error('升级累计消费下限');
        return;
      }
      if (
        this.ruleForm.degradeMoney == '' ||
        this.ruleForm.degradeMoney == null
      ) {
        this.$message.error('生日权益(倍积分)');
        return;
      }
      // if (this.ruleForm.firstScore == "") {
      //   this.$message.error("请输入首次达成礼(赠送积分)");
      //   return;
      // }

      if (this.ruleForm.degradeDay == '') {
        this.$message.error('请输入降级天数');
        return;
      }
      if (this.ruleForm.scoreRatio == '') {
        this.$message.error('请输入积分权益(倍积分)');
        return;
      }
      if (this.ruleForm.birthRatio == '') {
        this.$message.error('生日权益(倍积分)');
        return;
      }
      if (this.ruleForm.firstScore == '') {
        this.$message.error('请输入首次达成礼(赠送积分)');
        return;
      }
      if (this.ruleForm.levelNumber == '') {
        this.$message.error('请输入排序');
        return;
      }
      if (this.ruleForm.backgroundImage == '') {
        this.$message.error('请上传会员背景图片');
        return;
      }

      if (this.editflag) {
        var userId = localStorage.getItem('userId');
        let data = {
          uuid: this.uuid,
          gradelevelName: this.ruleForm.gradelevelName,
          //   status: this.ruleForm.status,
          //   gradelevelCode: this.ruleForm.gradelevelCode,
          gradelevelId: this.ruleForm.gradelevelId,
          createUser: this.ruleForm.createUser,
          updateUser: this.ruleForm.updateUser,
          yearTotalConsume: this.ruleForm.yearTotalConsume,
          oneTimeComsume: this.ruleForm.oneTimeComsume,
          degradeMoney: this.ruleForm.degradeMoney,
          degradeDay: this.ruleForm.degradeDay,
          scoreRatio: this.ruleForm.scoreRatio,
          birthRatio: this.ruleForm.birthRatio,
          firstScore: this.ruleForm.firstScore,
          levelNumber: this.ruleForm.levelNumber,
          backgroundImage: this.ruleForm.backgroundImage,
        };
        upmemberrule(data).then((res) => {
          this.dialogVisible = !this.dialogVisible;
          this.$message({
            showClose: true,
            message: '修改成功',
            type: 'success',
          });
          this._getmemberinfo();
        });
      } else {
        let data = {
          gradelevelName: this.ruleForm.gradelevelName,
          //   status: this.ruleForm.status,
          //   gradelevelCode: this.ruleForm.gradelevelCode,
          gradelevelId: this.ruleForm.gradelevelId,
          createUser: this.ruleForm.createUser,
          updateUser: this.ruleForm.updateUser,
          yearTotalConsume: this.ruleForm.yearTotalConsume,
          oneTimeComsume: this.ruleForm.oneTimeComsume,
          degradeMoney: this.ruleForm.degradeMoney,
          degradeDay: this.ruleForm.degradeDay,
          scoreRatio: this.ruleForm.scoreRatio,
          birthRatio: this.ruleForm.birthRatio,
          firstScore: this.ruleForm.firstScore,
          levelNumber: this.ruleForm.levelNumber,
          backgroundImage: this.ruleForm.backgroundImage,
        };
        addmemberrule(data).then((res) => {
          this.dialogVisible = false;
          this.$message({
            showClose: true,
            message: '添加成功',
            type: 'success',
          });
          this._getmemberinfo();
        });
      }
      //var u1 = "u1";
    },
    handleSizeChange(val) {
      this.listQuery.size = val;
      this.search();
    },
    handleCurrentChange(val) {
      this.listQuery.current = val;
      this.search();
    },
    _getmemberinfo() {
      let data = {
        size: this.listQuery.size,
        current: this.listQuery.current,
        condition: { gradelevelName: this.formInline.gradelevelName },
        ascs: [],
        descs: [],
      };
      getmemberrule(data).then((res) => {
        this.loading = false;
        this.tableData = res.records;
        this.tableData.gradeLevel = parseInt(res.records.gradeLevel);
        this.total = res.total;
        console.log(res, 'ppe');
      });
    },

    handlePictureCardPreview(file) {
      if (file.url) {
        this.$seeImage({
          currentTarget: {
            currentSrc: file.url,
          },
        });
      }
    },
    upLoadPic(file) {
      this.imgList = [];
      this.ruleForm.backgroundImage = file.result;
    },
    handleImgChange(file) {
      if (file.response) {
        this.imgList.push({
          url: file.response.result,
          status: 'finished',
        });
      }
    },

    handlePictureCardPreview(cur) {
      if(!cur.backgroundImage) {
        this.$message.error('当前会员等级未设置背景图')
        return
      }
      this.curImage = cur.backgroundImage;
      this.backgroundImageShow = true;
    }
  },
};
</script>
<style lang="less" scoped>
.toptitle {
  border: 1px solid #e0e0e0;
  border-bottom: 2px solid #188097;
  background: #f5f5f5;
  line-height: 35px;
  margin-bottom: 10px;
  padding: 0 10px;
  font-size: 14px;
  font-weight: bold;
}

.limttable {
  width: 500px;
  float: left;
}

.limttree {
  display: inline-block;

  border-top: 48px solid rgb(238, 241, 246);
  width: 206px;
  margin-left: 150px;
}

.toptitle {
  border: 1px solid #e0e0e0;
  border-bottom: 2px solid #188097;
  background: #f5f5f5;
  line-height: 35px;
  margin-bottom: 10px;
  padding: 0 10px;
  font-size: 14px;
  font-weight: bold;
}

.limttreecontain {
  height: 260px;
  width: 200px;
  overflow: scroll;
  border: 1px solid #ccc;
}

.demo-form-inline {
  //   border: 1px solid #ebeef5;
  padding: 20px 10px 3px 30px;
  margin-bottom: 25px;
}

.el-input {
  width: 50%;
}
</style>
